﻿using System;
using System.Collections.Concurrent;
using System.IO.Pipes;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;

namespace IoTSignalR
{

    public class NamePipeProtocol : IGeneralPipeProtocol
    {
        private readonly NamePipeServer _namePipeServer;
        //为了在中介者中选择协议去发送数据
        public event EventHandler<ProtocolNotifyEventArg> ReceiveMessagesAfter;
        public event EventHandler<ProtocolNotifyEventArg> SendMessagesAfter;
        public event EventHandler<ProtocolNotifyEventArg> OnConnectedAfter;
        public event EventHandler<ProtocolNotifyEventArg> OnDisconnectedAfter;
        public NamePipeProtocol(string pipeName)
        {
            _namePipeServer = new NamePipeServer(pipeName, PipeDirection.InOut,
                NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
            _namePipeServer.OnConnected += (sender, args) =>
            {
                OnConnectedAfter.Invoke(this, new ProtocolNotifyEventArg(args, ProtocolEnum.NamePipe));
            };
            _namePipeServer.OnDisconnected += (sender, args) =>
            {
                OnDisconnectedAfter.Invoke(this, new ProtocolNotifyEventArg(args, ProtocolEnum.NamePipe));
            };
            _namePipeServer.OnReceiveErro += (sender, args) =>
            {
                Console.WriteLine($"接收异常:{args.ClientId + " | " + args.Message}");
            };
            _namePipeServer.OnSendErro += (sender, args) =>
            {
                Console.WriteLine($"发送异常:{args.ClientId + " | " + args.Message}");
            };
            _namePipeServer.OnBusError += (sender, args) =>
            {
                Console.WriteLine($"总线错误:{args}");
            };
            _namePipeServer.ReceiveMessagesAfter += (sender, args) =>
            {
                ReceiveMessagesAfter.Invoke(this, new ProtocolNotifyEventArg(args, ProtocolEnum.NamePipe));
            };
            _namePipeServer.SendMessageAfter += (sender, args) =>
            {
                SendMessagesAfter.Invoke(this, new ProtocolNotifyEventArg(args, ProtocolEnum.NamePipe));
            };
            _namePipeServer.Start();
            Console.WriteLine($"命名管道协议{pipeName}已启动");
        }
        public async Task SendMsg(string clientId, string msg)
        {
            await _namePipeServer.SendMessage(clientId, msg);
        }
        public async Task SendGroupMsg(string clientId, string msg)
        {
            await _namePipeServer.SendGroupMessage(clientId, msg);
        }
    }
}
